﻿using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace MySqlStudent.UI.Controllers
{
    public class ErrorController : Controller
    {
        private ILogger<ErrorController> _logger;

        public ErrorController(ILogger<ErrorController> logger)
        {
            _logger = logger;
        }

        [Route("Error/{statusCode}")]
        public IActionResult HttpStatusCodeHandler(int statusCode)
        {
            var statusCodeResult = HttpContext.Features.Get<IStatusCodeReExecuteFeature>();
            switch (statusCode)
            {
                case 404:
                    ViewBag.ErrorMessage = "抱歉，读者访问的页面不存在";
                    _logger.LogWarning($"发生了一个404错误.路径 = " +
                        $"{statusCodeResult.OriginalPath} 以及查询字符串 = " +
                        $"{statusCodeResult.OriginalQueryString}");
                    break;
            }

            return View("NotFound");
        }

        // 把错误的信息写到数据库表里
        [Route("Error")]
        public IActionResult Error()
        {
            // 获取异常细节
            var exceptionHandler =
                HttpContext.Features.Get<IExceptionHandlerPathFeature>();

            _logger.LogError($"路径 {exceptionHandler.Path} " +
                $"产生了一个错误{exceptionHandler.Error}");

            return View("Error");
        }
    }
}